package com.warmlight.voicepacket.ui.user;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.OSSRequest;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.github.siyamed.shapeimageview.CircularImageView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.base.BaseActivity;
import com.warmlight.voicepacket.data.UserCenterData;
import com.warmlight.voicepacket.data.eventbus.Login;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.http.ResponseData;
import com.warmlight.voicepacket.utils.GlideImageLoader;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.TimeFormatUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TreeMap;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

/**
 * 用户资料编辑页面
 */
public class UserEditInformation extends BaseActivity {

    private Dialog mPicChsDialog;
    private static final int IMAGE_PICKER = 10;
    private ImagePicker imagePicker;
    private String headerImg = "";
    private RelativeLayout rl_header;
    private CircularImageView iv_header;
    private RelativeLayout rl_name;
    private EditText et_name;
    private RelativeLayout rl_sex;
    private TextView tv_sex;
    private RelativeLayout rl_birthday;
    private TextView tv_birthday;
    private EditText et_sign;
    private String timeInMillis = "0";
    private String sex;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_edit_information);
        initView();
        initlistener();
        initData();
    }

    private void initlistener() {
        rl_sex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShowSelectSexDialog();
            }
        });

        rl_birthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectBirthday();
            }
        });
    }

    private void selectBirthday(){
        Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR);
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

                Calendar startcal = Calendar.getInstance();
                startcal.set(Calendar.YEAR,year);
                startcal.set(Calendar.MONTH,month);
                startcal.set(Calendar.DAY_OF_MONTH,dayOfMonth);

//                TimePickerDialog dialog = new TimePickerDialog(AddClassActivity.this, new TimePickerDialog.OnTimeSetListener() {
//                    @Override
//                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//
//                        startcal.set(Calendar.HOUR_OF_DAY,hourOfDay);
//                        startcal.set(Calendar.MINUTE, minute);
                timeInMillis = (startcal.getTimeInMillis()/1000)+"";
                String date = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date(startcal.getTimeInMillis()));
                tv_birthday.setText(date);
//
//                    }
//                },0,0,false);
//                dialog.show();

            }
        },mYear,mMonth,mDay);

        datePickerDialog.getDatePicker().setMaxDate(c.getTimeInMillis());

        datePickerDialog.show();
    }

    @Override
    public void rightTextClick(){
        String name = et_name.getText().toString().trim();
        if (TextUtils.isEmpty(name)){
            showToast("昵称不能为空");
            return;
        }
        String url= HttpConfig.EDIT_PROFILE;
        TreeMap<String,String> map = new TreeMap<>();
        map.put("auth_key", SPUtils.getLoginAuthKey());
        map.put("avator",headerImg);
        map.put("nickname",et_name.getText().toString());
        map.put("sex",sex+"");
        map.put("birth",timeInMillis);
        map.put("sign",et_sign.getText().toString());
        HttpClient.getInstance().postRxAndroidAES(url,map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseData>() {
                    @Override
                    public void accept(ResponseData responseData) throws Exception {
                        EventBus.getDefault().post(new Login(true));
                        if (TextUtils.equals("200",responseData.getCode())){
                            showToast("保存信息成功");
                            /**
                             * 刷新用户缓存数据。
                             *
                             * @param userInfo 需要更新的用户缓存数据。
                             */
                            String avator;
                            if (!TextUtils.isEmpty(headerImg)){
                                avator=headerImg;
                            }else {
                                avator=SPUtils.getLoginUser().getAvator();
                            }
                            RongIM.getInstance().refreshUserInfoCache(new UserInfo(SPUtils.getLoginUid(), et_name.getText().toString(), Uri.parse(avator)));
                            finish();
                        }else{
                            showToast(responseData.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        showToast("保存信息失败，请重试");
                    }
                });
    }

    private void initData() {
        setTitle("编辑资料");
        setBack();
        setRightText("保存");

        UserCenterData.AuthorBean loginUser = SPUtils.getLoginUser();
        String avator = loginUser.getAvator();
        RequestOptions options = new RequestOptions();
        options.placeholder(R.drawable.icon_login_header);
        Glide.with(getContext()).asBitmap().load(avator).apply(options).into(iv_header);
        et_name.setText(loginUser.getNickname());
        et_name.setSelection(loginUser.getNickname().length());
        String sex = loginUser.getSex();
        if (TextUtils.isEmpty(sex) || TextUtils.equals("0",sex)){
            tv_sex.setText("性别保密");
        }else {
            tv_sex.setText(TextUtils.equals("1", sex) ? "男" : "女");
        }
//        String birth = loginUser.getBirth();
        String new_birth = loginUser.getNew_birth();
        if (TextUtils.equals("0",new_birth)){
            Calendar c = Calendar.getInstance();
            int mYear = c.get(Calendar.YEAR);
            int mMonth = c.get(Calendar.MONTH)+1;
            int mDay = c.get(Calendar.DAY_OF_MONTH);
            tv_birthday.setText(mYear+"-"+mMonth+"-"+mDay);
        }else {
            tv_birthday.setText(TimeFormatUtils.stringToString(new_birth+"000","yyyy-MM-dd"));
        }
        String sign = loginUser.getSign();
        if (TextUtils.isEmpty(sign)){
            et_sign.setHint("这个人还没有个性签名哦");
        }else{
            et_sign.setText(sign);
        }

        this.sex = loginUser.getSex();
        timeInMillis = new_birth;



        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(false);  //显示拍照按钮
        imagePicker.setMultiMode(false);//单选
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素


//        imagePicker = ImagePicker.getInstance();
//        imagePicker.setImageLoader(new GlideImageLoader());
//        imagePicker.setMultiMode(false);
//        imagePicker.setShowCamera(true);
//        imagePicker.setCrop(true);
//        imagePicker.setSaveRectangle(true);
//
//        imagePicker.setStyle(CropImageView.Style.CIRCLE);
//        Integer radius = Integer.valueOf(140);
//        radius = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, radius, getResources().getDisplayMetrics());
//        imagePicker.setFocusWidth(radius * 2);
//        imagePicker.setFocusHeight(radius * 2);
//        imagePicker.setOutPutX(Integer.valueOf(800));
//        imagePicker.setOutPutY(Integer.valueOf(800));
    }

    private void initView() {

        rl_header = (RelativeLayout) findViewById(R.id.rl_header);
        iv_header = (CircularImageView) findViewById(R.id.iv_header);
        rl_name = (RelativeLayout) findViewById(R.id.rl_name);
        et_name = (EditText) findViewById(R.id.et_name);
        rl_sex = (RelativeLayout) findViewById(R.id.rl_sex);
        tv_sex = (TextView) findViewById(R.id.tv_sex);
        rl_birthday = (RelativeLayout) findViewById(R.id.rl_birthday);
        tv_birthday = (TextView) findViewById(R.id.tv_birthday);
        et_sign = (EditText) findViewById(R.id.et_sign);
        rl_header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserEditInformation.this, ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
            }
        });

    }

    /**
     * 图片选择对话框
     */
    private void initPhotoDialog() {
        mPicChsDialog = new Dialog(this, R.style.floag_dialog);
        mPicChsDialog.setContentView(R.layout.dialog_pic_choose);

        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        Window dlgwin = mPicChsDialog.getWindow();
        WindowManager.LayoutParams lp = dlgwin.getAttributes();
        dlgwin.setGravity(Gravity.BOTTOM);
        lp.width = (int) (display.getWidth()); //设置宽度

        mPicChsDialog.getWindow().setAttributes(lp);

        TextView camera = (TextView) mPicChsDialog.findViewById(R.id.chos_camera);
        camera.setVisibility(View.GONE);
        TextView picLib = (TextView) mPicChsDialog.findViewById(R.id.pic_lib);
        TextView cancel = (TextView) mPicChsDialog.findViewById(R.id.btn_cancel);
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                getPicFrom(CAPTURE_IMAGE_CAMERA);
                mPicChsDialog.dismiss();
            }
        });

        picLib.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                getPicFrom(IMAGE_STORE);
                mPicChsDialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPicChsDialog.dismiss();
            }
        });
    }


    /**
     * 选择性别对话框
     */
    private void ShowSelectSexDialog(){
        final AlertDialog dialog = new AlertDialog.Builder(this,R.style.ConfirmDialogStyle).create();


        View view_ss = getLayoutInflater().inflate(R.layout.view_selet_sex, null);
        dialog.setView(view_ss, 0, 0, 0, 0);

        int width = getWindowManager().getDefaultDisplay().getWidth();
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = width;
        params.height =  WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.CENTER;
        dialog.getWindow().setAttributes(params);

        Button btn_male = (Button) view_ss.findViewById(R.id.btn_ss_male);
        btn_male.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                TCUserInfoMgr.getInstance().setUserSex(TIMFriendGenderType.Male, new ITCUserInfoMgrListener() {
//                    @Override
//                    public void OnQueryUserInfo(int error, String errorMsg) {
//
//                    }
//
//                    @Override
//                    public void OnSetUserInfo(int error, String errorMsg) {
//                        if (0 != error)
//                            Toast.makeText(getApplicationContext(),"设置性别失败" + errorMsg,Toast.LENGTH_LONG).show();
//                        else
//                            lcvSelectSex.setContent(TCUtils.EnumGenderToString(TIMFriendGenderType.Male));
//                    }
//                });
                sex = "1";
                tv_sex.setText("男");
                dialog.dismiss();
            }
        });

        Button btn_female = (Button) view_ss.findViewById(R.id.btn_ss_female);
        btn_female.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                TCUserInfoMgr.getInstance().setUserSex(TIMFriendGenderType.Female, new ITCUserInfoMgrListener() {
//                    @Override
//                    public void OnQueryUserInfo(int error, String errorMsg) {
//
//                    }
//
//                    @Override
//                    public void OnSetUserInfo(int error, String errorMsg) {
//                        if (0 != error)
//                            Toast.makeText(getApplicationContext(),"设置性别失败" + errorMsg,Toast.LENGTH_LONG).show();
//                        else
//                            lcvSelectSex.setContent(TCUtils.EnumGenderToString(TIMFriendGenderType.Female));
//                    }
//                });
                sex = "2";
                tv_sex.setText("女");
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size()>0){
                    ImageItem imageItem = images.get(0);
                    Glide.with(getContext()).asBitmap().load(imageItem.path).into(iv_header);
                    asyncPutImage(imageItem.path);
                }
            } else {
                showToast( "没有数据");
            }
        }
    }

    private ProgressDialog progressDialog;
    //android.R.style.Theme_Material_Light_Dialog_Alert
    private void showProgressDialog(String msg){
        if (progressDialog != null && progressDialog.isShowing()){
            return;
        }
        if (progressDialog == null){
            progressDialog = new ProgressDialog(this,android.R.style.Theme_Material_Light_Dialog_Alert);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.setMessage(msg);

        progressDialog.show();
    }

    private void hideProgressDialog(){
        if (progressDialog != null){
            if (progressDialog.isShowing()){
                progressDialog.dismiss();
            }
        }
    }
    public void asyncPutImage( String localFile) {

        String endpoint = HttpConfig.endpoint;
//        String stsServer = "STS应用服务器地址，例如http://abc.com";
//推荐使用OSSAuthCredentialsProvider。token过期可以及时更新
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(HttpConfig.accessKeyId,HttpConfig.accessKeySecret);
//该配置类如果不设置，会有默认配置，具体可看该类
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS mOss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
        final long upload_start = System.currentTimeMillis();
        final String object = HttpConfig.objectName()+"avator"+ TimeFormatUtils.getCurrentTimeMillis()+".png";
        if (object.equals("")) {
            Log.w("AsyncPutImage", "ObjectNull");
            return;
        }

        File file = new File(localFile);
        if (!file.exists()) {
            Log.w("AsyncPutImage", "FileNotExist");
            Log.w("LocalFile", localFile);
            return;
        }

        showProgressDialog("图片上传中");
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(HttpConfig.bucket, object, localFile);
        put.setCRC64(OSSRequest.CRC64Config.YES);
//        if (mCallbackAddress != null) {
//            // 传入对应的上传回调参数，这里默认使用OSS提供的公共测试回调服务器地址
//            put.setCallbackParam(new HashMap<String, String>() {
//                {
//                    put("callbackUrl", mCallbackAddress);
//                    //callbackBody可以自定义传入的信息
//                    put("callbackBody", "filename=${object}");
//                }
//            });
//        }

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                int progress = (int) (100 * currentSize / totalSize);
//                mDisplayer.updateProgress(progress);
//                mDisplayer.displayInfo("上传进度: " + String.valueOf(progress) + "%");

            }
        });

        OSSAsyncTask task = mOss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");

                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());

                long upload_end = System.currentTimeMillis();
                OSSLog.logDebug("upload cost: " + (upload_end - upload_start) / 1000f);
//                mDisplayer.uploadComplete();
//                mDisplayer.displayInfo("Bucket: " + mBucket
//                        + "\nObject: " + request.getObjectKey()
//                        + "\nETag: " + result.getETag()
//                        + "\nRequestId: " + result.getRequestId()
//                        + "\nCallback: " + result.getServerCallbackReturnBody());
                headerImg = HttpConfig.ali+object;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideProgressDialog();
                        showToast("头像上传成功");
                    }
                });
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                String info = "";
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    info = clientExcepion.toString();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                    info = serviceException.toString();
                }
//                mDisplayer.uploadFail(info);
//                mDisplayer.displayInfo(info);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideProgressDialog();
                        showToast("头像上传失败，请重试");
                    }
                });

            }
        });
    }

}
